#include <common.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <mqtt_paho.h>
#include <server.h>
#include <tpunb.h>
#include <system.h>
#include <devnode.h>

static struct mqtt_client mqtt_cli;

static char gw_sn[128] = {0};
static char terminal_gwsn[128] = {0};

char *get_gw_sn(void)
{
	return gw_sn;
}

char *get_terminal_gwsn(void)
{
	return terminal_gwsn;
}

void get_gw_devSn(char *devSn)
{
	strcpy(devSn, gw_sn);
}

const char mmap_table[] = 
{
	'3','n','7','9','0','B','a','b','O','S','0','0','0','0','0','0','0',
	'Y','d','f','X','g','D','h','i','F','j','k','2','m','p','8','r','s',
	't','c','v','V','x','z','A','q','C','0','0','0','0','0','0','E','6',
	'G','W','J','e','K','y','L','N','P','Q','1','R','4','T','H','w','U',
	'5','M','Z','u','o','O','5','F','s','i','p','1','7','c','w','A'
};

int mqtt_client_publish_data(char *topic, unsigned char *msg, int msglen)
{
	if(mqtt_paho_publish(topic, msg, msglen, DEFAULT_MQTT_QOS) == 0)
	{
		return 0;
	}
	
	return -1;
}

int mqtt_client_topic_subscribe(char *topic, int subscribe)
{
	if(mqtt_paho_subscribe(topic, subscribe, DEFAULT_MQTT_QOS) == 0)
	{
		return 0;
	}

	return -1;
}

int mqtt_client_connect_ok(void)
{
	if(mqtt_paho_connect())
	{
		return 1;
	}
	
	return 0;
}

static int mqtt_server_message_handle(char *topicName, void *data, int len)
{
	handle_server_data(topicName, data, len);
	return 0;
}

//mqtt链接成功回调接口
static void mqtt_server_connect_handle(void)
{
	DEBUG("mqtt_server_connect_handle");
	//devNode_publish_all_to_server();
	start_scan_online_thread();
	gw_heartBeat_to_server();

	// /etc/init.d/S49ntp restart
	myexec("/etc/init.d/S49ntp restart", NULL, NULL);
}

void get_dev_info_desc(char *device_sn, char *device_key, char *tpunb_sn)
{
	int ret = 0;
	cJSON *root;
	cJSON *value;

	char chipid_str[24] = {0};
	get_serial_number(chipid_str);

	root = parse_root_from_file(DEV_FILE);
	if(root)
	{
		//device_sn
		value = cJSON_GetObjectItem(root, "gwid");
		if(value)
		{
			if(strcmp(value->valuestring, "FFFFFFFFFFFFF") != 0) 
			{
				strcpy(device_sn, value->valuestring);
				strcpy(gw_sn, device_sn);
				ret = 1;
			}
		}

		free_root(root);
	}

	if(ret == 0)
	{
		strcpy(device_sn, chipid_str);
		strcpy(gw_sn, device_sn);
	}
}

void replace_gw_devSn(char *dev_sn)
{
	cJSON *root;
	cJSON *value;

	char sn[24] = {0};
	
	root = parse_root_from_file(DEV_FILE);
	if(root)
	{
		strncpy(sn, dev_sn, 13);
		strcpy(gw_sn, sn);

		value = cJSON_GetObjectItem(root, "gwid");
		if(value)
		{
			cJSON_ReplaceItemInObject(root, "gwid", cJSON_CreateString(sn));
		}

		save_root_to_file(root, DEV_FILE);
		free_root(root);
	}
}

int set_terminal_gwsn(char *dev_sn)
{
	cJSON *root;
	cJSON *value;

	root = parse_root_from_file(DEV_FILE);
	if(root)
	{
		value = cJSON_GetObjectItem(root, "terminalgwid");
		if(value)
		{
			cJSON_ReplaceItemInObject(root, "terminalgwid", cJSON_CreateString(dev_sn));
		}
		else
		{
			cJSON_AddStringToObject(root, "terminalgwid", dev_sn);
		}

		strcpy(terminal_gwsn, dev_sn);

		save_root_to_file(root, DEV_FILE);
		free_root(root);
		return 0;
	}

	return -1;
}

static void get_terminal_gwid(void)
{
	cJSON *root;
	cJSON *value;

	root = parse_root_from_file(DEV_FILE);
	if(root)
	{
		value = cJSON_GetObjectItem(root, "terminalgwid");
		if(value)
		{
			strcpy(terminal_gwsn, value->valuestring);
		}
		else
		{
			strcpy(terminal_gwsn, gw_sn);
		}

		free_root(root);
	}
}

static int get_urandom(char *random_buf, int len)
{
	unsigned char buffer[512] = {0};
	
	int fd = open("/dev/urandom", O_RDONLY);
	if(fd > 0) {
		read(fd, buffer, len);
		close(fd);
	}

	hex2string(random_buf, buffer, len);

	return 0;
}

int mqtt_client_info_init(char *user_name, char *pass_wd, char *client_id, char *gwid)
{
	char random_buf[128] = {0};
	char device_sn[128] = {0};
	char clientid[512] = {0};

	get_dev_info_desc(device_sn, NULL, NULL);

	get_terminal_gwid();
	
	get_urandom(random_buf, 16);

	sprintf(clientid, "%s_%s", device_sn, random_buf);

	strcpy(client_id, clientid);
	strcpy(gwid, device_sn);

	strcpy(user_name, MQTT_USER_NAME);
	strcpy(pass_wd, MQTT_PASSWD);

	DEBUG("user_name=%s", user_name);
	DEBUG("pass_wd=%s", pass_wd);
	DEBUG("client_id=%s", client_id);

	return 0;
}


void mqtt_client_init(void)
{
	strcpy(mqtt_cli.host, DEFAULT_MQTT_SER);
	mqtt_cli.port = DEFAULT_MQTT_PORT;
	mqtt_cli.keepAlive = DEFAULT_MQTT_KEEPALIVE;
	mqtt_cli.qos = DEFAULT_MQTT_QOS;
	mqtt_cli.mqtt_msg_handle_callback = mqtt_server_message_handle;
	mqtt_cli.mqtt_connect_handle_callback = mqtt_server_connect_handle;
	mqtt_client_info_init(mqtt_cli.username, mqtt_cli.password, mqtt_cli.clientid, mqtt_cli.gwid);

	mqtt_paho_start(&mqtt_cli);
}

void mqtt_client_reconnect(void)
{
	DEBUG("set mqtt_client_reconnect");
	mqtt_paho_reconnect();
}
